package org.hk.kg.web;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hk.kg.utils.Constants;
import org.hk.kg.utils.LocalResouce;
import org.hk.kg.utils.XMLUtils;
import org.jdom.Element;

public class HtmlRenderUtils {
	private static Log log = LogFactory.getLog(HtmlRender.class);
	
	public static HtmlRenderUtils instance = new HtmlRenderUtils();
	private List<HtmlRender> rendersLink;
	
	public HtmlRenderUtils()
	{	
		this.initailize();
	}
	
	private void initailize()
	{
		rendersLink = new LinkedList<HtmlRender>();
		try {
			Element rendersElement = XMLUtils.getElementFromDoc(
					XMLUtils.getDocument(LocalResouce.getConfigFile(Constants.UI_CONFIG)), 
					Constants.UI_CONFIG_RENDERS_TAG);
			for(Iterator rendersChild = rendersElement.getChildren().iterator();
				rendersChild.hasNext();)
			{
				Element childElement = (Element) rendersChild.next();
				String clzzName = childElement.getAttributeValue(Constants.UI_CONFIG_RENDER_CLASS_ATTR);
				Class<HtmlRender> render = (Class<HtmlRender>) ClassLoader.getSystemClassLoader().loadClass(clzzName);
				rendersLink.add(render.newInstance());
			}
		} catch (Exception e) {
			//TODO : 渲染器创建失败
		}
	}
	
	public String render(String line,BaseAction context)
	{
		Iterator<HtmlRender> iterator = rendersLink.iterator();
		HtmlRender render = null;
		String rendered = line;
		if(iterator.hasNext())
		{
			render = iterator.next();
		}
		while(render != null)
		{
			if(render.validate(line))
			{
				rendered = render.execute(line, context);
			}
			
			if(iterator.hasNext())
			{
				render = iterator.next();
			}
			else
			{
				render = null;
			}
		}
		return rendered;
	}
}
